package com.tansun.tandata.service.impl;

import com.tansun.tandata.entity.*;
import com.tansun.tandata.mapper.ApprovalDao;
import com.tansun.tandata.mapper.UserDao;
import com.tansun.tandata.service.ApprovalService;
import com.tansun.tandata.utils.ParentServiceImp;
import com.tansun.tandata.utils.ResponseBase;
import com.tansun.tandata.utils.StringUtil;
import com.tansun.tandata.vo.req.ApprovalPageVo;
import com.tansun.tandata.vo.res.UserRoleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Service
public class ApprovalServiceImpl extends ParentServiceImp<ApprovalDao, Approval> implements ApprovalService {
    @Autowired
    private ApprovalDao approvalDao;
    @Autowired
    private UserDao userDao;
    @Value("${sys.role.salesRoleId}")
    private String salesRoleId;
    @Value("${sys.role.approvalRoleId}")
    private String approvalRoleId;
    @Override
    public ResponseBase addApproval(Approval approval) {
        ResponseBase responseBase = new ResponseBase();
        //根据业务人员查重
        if(approvalDao.selectContBysalesName(approval.getSales_name())>0){
            //业务人员姓名重复
            responseBase.setCode(200);
            responseBase.setMsg("添加的业务人员已经存在");
            return responseBase;
        }
        approval.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        approval.setCreateTime(new Date());
        //储存子表
        if(!StringUtil.isEmpty(approval.getApproval())){
            StringBuffer approval_nick_nameBf = new StringBuffer();
            ArrayList<ApprovalSon> userList =  new ArrayList<>();
            String[] users = approval.getApproval().split(";");
            String userCode = "";
            String username="";
            for(int i =0;i<users.length;i++){
                String userStr = users[i];
                if(StringUtil.isEmpty(userStr)){
                    continue;
                }
                ApprovalSon obj = new ApprovalSon();
                obj.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                obj.setApproval(userStr.substring(0,userStr.indexOf(",")));
                obj.setSales_name(approval.getSales_name());
                approval_nick_nameBf.append(","+userStr.substring(userStr.indexOf(",")+1));
                userList.add(obj);
            }
            approval.setApproval_nick_name(approval_nick_nameBf.toString().substring(1));
            //批量保存子表
            approvalDao.insertApprovalSonBath(userList);
        }
        //保存主表
        approvalDao.insert(approval);
        responseBase.setCode(200);
        responseBase.setMsg("新建成功");
        return responseBase;
    }

    @Override
    public ResponseBase updateApproval(Approval approval) {
        ResponseBase responseBase = new ResponseBase();
        //根据业务人员查重
        Approval oldApproval = approvalDao.selectByPrimaryKey(approval.getId());
        if(oldApproval==null){
            //业务人员姓名重复
            responseBase.setCode(-1);
            responseBase.setMsg("记录不存在");
            return responseBase;

        }
        if(!oldApproval.getSales_name().equals(approval.getSales_name())) {
            if (approvalDao.selectContBysalesName(approval.getSales_name()) > 0) {
                //业务人员姓名重复
                responseBase.setCode(200);
                responseBase.setMsg("添加的业务人员已经存在");
                return responseBase;
            }
        }
        //储存子表
        if(!StringUtil.isEmpty(approval.getApproval())){
            StringBuffer approval_nick_nameBf = new StringBuffer();
            ArrayList<ApprovalSon> userList =  new ArrayList<>();
            String[] users = approval.getApproval().split(";");
            String userCode = "";
            String username="";
            for(int i =0;i<users.length;i++){
                String userStr = users[i];
                if(StringUtil.isEmpty(userStr)){
                    continue;
                }
                ApprovalSon obj = new ApprovalSon();
                obj.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                obj.setApproval(userStr.substring(0,userStr.indexOf(",")));
                obj.setSales_name(approval.getSales_name());
                approval_nick_nameBf.append(","+userStr.substring(userStr.indexOf(",")+1));
                userList.add(obj);
            }
            approval.setApproval_nick_name(approval_nick_nameBf.toString().substring(1));
            //删除旧的子表
            approvalDao.deleteApprovalSonBysalesName(approval.getSales_name());
            //批量保存子表
            approvalDao.insertApprovalSonBath(userList);
        }
        //保存主表
        approvalDao.updateByPrimaryKeySelective(approval);
        responseBase.setCode(200);
        responseBase.setMsg("修改");
        return responseBase;
    }

    @Override
    public List<Approval> getApploval(ApprovalPageVo vo) {
        return approvalDao.getApproval(vo);
    }

    @Override
    public Integer deleteApproval(String id) {
        Approval obj = approvalDao.selectByPrimaryKey(id);
        if(obj!=null&&!StringUtil.isEmpty(obj.getSales_name())){
            //删除子表
            approvalDao.deleteApprovalSonBysalesName(obj.getSales_name());
        }
        return approvalDao.deleteByPrimaryKey(id);
    }

    @Override
    public ResponseBase authUserApprovalRole(String loginName) {
        //根据登录名查询用户信息
        User user= userDao.findUserByName(loginName);
        int isSales =approvalDao.selectContBysalesName(loginName);
        int isApproval =approvalDao.selectSonContByApproval(loginName);
        int salesRoleCont =approvalDao.selectRoleCont(user.getUserCode(),salesRoleId);
        int approvalRoleCont=approvalDao.selectRoleCont(user.getUserCode(),approvalRoleId);
        List<Role> resultRole = new ArrayList<>();
        //同部业务人员角色
        if(isSales>0){
            //登录用户是业务人员的场合
            if(salesRoleCont<=0){
                //给用户添加业务角色
                UserRole userRole = new UserRole();
                userRole.setUserCode(user.getUserCode());
                Role role = new Role();
                role.setRoleCode(salesRoleId);
                List<Role> roles = new ArrayList<>();
                roles.add(role);
                userRole.setRoles(roles);
                userDao.saveUserRole(userRole);
                resultRole.addAll(roles);
            }
        }else{
            //登录人员不是业务人员的场合
            if(salesRoleCont>0){
                //给登录人员删除业务人员角色
                approvalDao.deleteUserRole(user.getUserCode(),salesRoleId);
            }
        }

        //同步审批人员权限
        if(isApproval>0){
            //登录用户是审批人员的场合
            if(approvalRoleCont<=0){
                //给用户添加审批角色
                UserRole userRole = new UserRole();
                userRole.setUserCode(user.getUserCode());
                Role role = new Role();
                role.setRoleCode(approvalRoleId);
                List<Role> roles = new ArrayList<>();
                roles.add(role);
                userRole.setRoles(roles);
                userDao.saveUserRole(userRole);
                resultRole.addAll(roles);
            }
        }else {
            //登录人员不是审批人员的场合
            if(approvalRoleCont>0){
                //给登录人员删除业务人员角色
                approvalDao.deleteUserRole(user.getUserCode(),approvalRoleId);
            }
        }
        ResponseBase result = new ResponseBase();
        result.setMsg("授权成功");
        result.setData(resultRole);
        result.setCode(200);
        return result;
    }

    @Override
    public List<Role> authUserApprovalRole(UserRoleVO user) {
        int isSales =approvalDao.selectContBysalesName(user.getLoginName());
        int isApproval =approvalDao.selectSonContByApproval(user.getLoginName());
        int salesRoleCont =approvalDao.selectRoleCont(user.getUserCode(),salesRoleId);
        int approvalRoleCont=approvalDao.selectRoleCont(user.getUserCode(),approvalRoleId);
        List<Role> resultRole = new ArrayList<>();
        //同部业务人员角色
        if(isSales>0){
            //登录用户是业务人员的场合
            if(salesRoleCont<=0){
                //给用户添加业务角色
                UserRole userRole = new UserRole();
                userRole.setUserCode(user.getUserCode());
                Role role = new Role();
                role.setRoleCode(salesRoleId);
                List<Role> roles = new ArrayList<>();
                roles.add(role);
                userRole.setRoles(roles);
                userDao.saveUserRole(userRole);
                resultRole.addAll(roles);
            }
        }else{
            //登录人员不是业务人员的场合
            if(salesRoleCont>0){
                //给登录人员删除业务人员角色
                approvalDao.deleteUserRole(user.getUserCode(),salesRoleId);
            }
        }
        //同步审批人员权限
        if(isApproval>0){
            //登录用户是审批人员的场合
            if(approvalRoleCont<=0){
                //给用户添加审批角色
                UserRole userRole = new UserRole();
                userRole.setUserCode(user.getUserCode());
                Role role = new Role();
                role.setRoleCode(approvalRoleId);
                List<Role> roles = new ArrayList<>();
                roles.add(role);
                userRole.setRoles(roles);
                userDao.saveUserRole(userRole);
                resultRole.addAll(roles);
            }
        }else {
            //登录人员不是审批人员的场合
            if(approvalRoleCont>0){
                //给登录人员删除业务人员角色
                approvalDao.deleteUserRole(user.getUserCode(),approvalRoleId);
            }
        }
        return resultRole;
    }
}
